const loginMethods = {
  /**
   * 刷新token
   */
  refreshToken: async () => {
    http.request({
      url: `/token/refresh?refreshToken=${uni.getStorageSync('refreshToken')}`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        refreshToken: uni.getStorageSync('refreshToken')
      },
      login: true,
      isRefreshing: true,
      dontTrunLogin: true
    }).then(res => {
      console.log('刷新token成功', res);

      uni.setStorageSync('isRefreshingToken', false)
      uni.setStorageSync('expiresTimeStamp', res.data.expiresIn * 1000 / 2 + new Date().getTime())
      uni.setStorageSync('Token', res.data.accessToken) // 把token存入缓存，请求接口数据时要用
      uni.setStorageSync('refreshToken', res.data.refreshToken) // 把token存入缓存，请求接口数据时要用
    }).catch((err) => {
      console.log('刷新token失败', err);

      uni.setStorageSync('isRefreshingToken', false)
      uni.removeStorageSync('Token')
      uni.removeStorageSync('expiresTimeStamp')
      uni.removeStorageSync('isRefreshingToken')
      uni.removeStorageSync('routeUrlAfterLogin')
      uni.showToast({
        title: '登录过期，请重新登录',
        icon: 'none'
      })
      uni.reLaunch({
        url: '/pages/accountLogin/accountLogin'
      })
    })
  },

  /**
   * 设置登录后的跳转地址
   */
  setRouteUrlAfterLogin: () => {
    const pages = getCurrentPages()
    // 登录后的回跳地址
    if (pages[pages.length - 1].route.indexOf('user-login') === -1) {
      uni.setStorageSync('routeUrlAfterLogin', pages[pages.length - 1].$page.fullPath)
    }
  }
}

export default loginMethods
